package com.otitan.la.forest.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.constant.BaseParamConstant;
import com.otitan.la.forest.system.constant.StaticConstant;
import com.otitan.la.forest.system.dto.BaseParamDTO;
import com.otitan.la.forest.system.entity.BaseParamEntity;
import com.otitan.la.forest.system.mapper.BaseParamMapper;
import com.otitan.la.forest.system.service.BaseParamService;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class BaseParamServiceImpl extends ServiceImpl<BaseParamMapper, BaseParamEntity> implements BaseParamService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${redis.key-prefix}")
    private String redisKeyPrefix;

    @Override
    public DataResult findPageData(long page, long size, BaseParamDTO baseParam) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<BaseParamEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        //queryWrapper.eq(BaseParamEntity::getId, baseParam.getId());
        IPage<BaseParamEntity> iPage = this.page(pagePlug, queryWrapper);
        return DataResult.success(iPage);
    }

    @Override
    public Long getUserLoginErrorNum(String userName) {
        String value = redisTemplate.opsForValue().get(redisKeyPrefix + StaticConstant.LOGIN_ERROR_NUM_FLAG + userName);
        if (value ==null){
            return 0L;
        }
        return Long.parseLong(value) - 1;
    }

    @Override
    public Long addUserLoginErrorNum(String userName) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(redisKeyPrefix + StaticConstant.LOGIN_ERROR_NUM_FLAG + userName, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        //自增长从1开始
        if (increment < 1) {
            increment = entityIdCounter.getAndIncrement();
        }
        // 登录超时用户锁定时间
        Integer liveTime = 30;
        //初始设置过期时间
        if (null == increment || increment.longValue() == 0 || increment.longValue() == 1) {
            entityIdCounter.expire(liveTime, TimeUnit.MINUTES);
        }
        return increment;
    }

    @Override
    public Boolean removeUserLoginError(String userName) {
        String key = redisKeyPrefix + StaticConstant.LOGIN_ERROR_NUM_FLAG + userName;
        return redisTemplate.delete(key);
    }

    @Override
    public BaseParamEntity findOne(String id) {
        // 从Redis中获取
        String val = redisTemplate.opsForValue().get(redisKeyPrefix + BaseParamConstant.BASE_PARAM + id);
        if (StrUtil.isNotEmpty(val)){
            return JSONObject.parseObject(val, BaseParamEntity.class);
        }
        // 从数据中查询
        BaseParamEntity one = this.getById(id);
        // 缓存Redis
        redisTemplate.opsForValue().set(redisKeyPrefix + BaseParamConstant.BASE_PARAM + id,
                JSONObject.toJSONString(one),
                12,TimeUnit.HOURS);
        return one;
    }

    @Override
    public DataResult editor(BaseParamEntity entity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean isSuccess = this.updateById(entity);

        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }
}